<template>
  <div id="main">
    <h2>学生临床信息</h2>
    <div class="head">
      <el-input v-model="searchTableInfo" placeholder="请输入搜索内容" style="width:240px;float: right;margin-right:20px;" />
    </div>
    <div id="table-area">
      <el-table
        v-loading="listLoading"
        :data="list.slice((currentPage - 1) * pagesize, currentPage * pagesize)"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
      >
        <el-table-column
          label="序号"
          type="index"
          align="center"
        >
          <template scope="scope">
            <span>{{ (currentPage - 1) * pagesize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="studentId"
          label="ID号"
        />

        <el-table-column
          align="center"
          prop="studentName"
          label="姓名"
        />

        <el-table-column
          align="center"
          prop="studentAge"
          :formatter="formatAge"
          label="年龄"
        />

        <el-table-column
          align="center"
          prop="studentTreatCurrentDiagnosis"
          label="临床诊断"
        />
        <el-table-column
          align="center"
          prop="studentTreatPrincipalTeacherName"
          label="主责老师"
        />
        <el-table-column
          align="center"
          prop="studentTreatPrincipalTeacherName"
          label="教学主管"
        />

        <el-table-column align="center" label="操作">
          <template slot-scope="Scope">
            <el-button type="primary" icon="el-icon-search" @click="handleOpen('修改孩子', 2, Scope.row.studentId)">查看</el-button>

          </template>
        </el-table-column>
      </el-table>

      <div id="pages">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[5, 10]"
          :page-size="pagesize"
          layout="total, sizes,prev, pager, next"
          :total="list.length"
          prev-text="上一页"
          next-text="下一页"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- --------------------------------------------------------------------------------------------------------- -->

    <el-dialog title="" :close-on-click-modal="false" :visible.sync="dialogFormVisible" :before-close="handleClose">
      <el-form ref="student" :model="student" label-position="top" :rules="rules">

        <el-form-item prop="studentTreatCurrentDiagnosis" label="临床诊断" :label-width="formLabelWidth">
          <el-input
            v-model="student.studentTreatCurrentDiagnosis"
            autocomplete="off"
            maxlength="500"
            show-word-limit
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 20 }"
            placeholder="请输入内容"
          />
        </el-form-item>

        <el-form-item prop="studentTreatHospital" label="就诊医院" :label-width="formLabelWidth">
          <el-input
            v-model="student.studentTreatHospital"
            autocomplete="off"

            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item
          label="诊断时间"
          :label-width="formLabelWidth"
          prop="studentTreatTime"
        >
          <el-date-picker
            v-model="student.studentTreatTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期时间"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item prop="studentTreatDiagnosisCases" label="诊断病例" :label-width="formLabelWidth">
          <el-input
            v-model="student.studentTreatDiagnosisCases"
            autocomplete="off"
            maxlength="500"
            show-word-limit
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 20 }"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item prop="studentTreatTrainingAge" label="起训年龄" :label-width="formLabelWidth">
          <el-input
            v-model="student.studentTreatTrainingAge"
            autocomplete="off"

            placeholder="请输入内容"
          />
        </el-form-item>

        <el-form ref="train" label-position="top" :inline="true" :model="train" label-width="100px">

          <el-form-item label="既往训练机构记录" :inline="true" :label-width="formLabelWidth">
            <el-button icon="el-icon-plus" circle size="small" style="margin-left: 20px" @click="addTrains()" />
            <div v-for="(item, index) in train" :key="index">
              <el-form-item label="训练时间" style="margin-right:0px">
                <el-col :span="11">
                  <el-form-item :prop="'train.'+index+'.timeStart'">
                    <el-date-picker v-model="item.timeStart" value-format="yyyy-MM-dd" type="date" style="width: 140px;" />
                  </el-form-item>
                </el-col>
                <el-col :span="11" style="margin-left:5px;">
                  <el-form-item :prop="'train.'+index+'.timeEnd'">
                    <el-date-picker v-model="item.timeEnd" value-format="yyyy-MM-dd" type="date" style="width: 140px;" />
                  </el-form-item>
                </el-col>
              </el-form-item>
              <el-form-item label="机构名称" :prop="'train.'+index+'.orgName'">
                <el-input v-model="item.orgName" clearable style="width:200px;" class="el-in-left-more" />
              </el-form-item>
              <el-form-item label="效果" :prop="'train.'+index+'.effect'" style="margin-left:8px">
                <el-input v-model="item.effect" clearable style="width:220px;" class="el-in-left-more" />
              </el-form-item>
              <el-button style="margin-top:50px" type="danger" icon="el-icon-delete" circle @click="deleteItem(item, index)" />
            </div>
          </el-form-item>
        </el-form>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleClose">取 消</el-button>
        <el-button v-if="editType == 2" type="primary" @click="handleUpdate('student')">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addChild, deleteChild, newUpdate, getAllMedicalChild, getChildById, getAllParent } from '@/api/child'
import { addFather, addMother } from '@/api/parent'
import store from '@/store/index'
export default {
  data() {
    return {
      BB: store.getters.userId,
      url: process.env.VUE_APP_BASE_API + 'file/',
      form: [],
      formRules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^1[34578]\d{9}$/,
            message: '目前只支持中国大陆的手机号码'
          }
        ]
      },
      sex: [
        {
          value: 0,
          label: '女'
        },
        {
          value: 1,
          label: '男'
        }
      ],
      father: [],
      mother: [],
      String: [],
      currentPage: 1, // 默认显示页面为1
      pagesize: 5, //    每页的数据条数
      // list: [],
      imageUrl: '',
      tableList: [],
      searchTableInfo: '',

      train_id: [],
      trainingInstitutionRecordId: '',
      listLoading: false,
      dialogFormVisible: false,
      is_add_father: false,
      is_add_mother: false,
      is_add_train: false,
      this_stuid: '',
      jurisdiction: [],
      editType: 1, // 1 添加 2 修改
      student: [],
      train: [],
      formLabelWidth: '200px',
      rules: {
        childIdcard: [
          { required: true, message: '证件号不能为空', trigger: 'blur' }
        ],
        childMedicalInfo: [
          { required: true, message: '医疗信息不能为空', trigger: 'blur' }
        ],
        childName: [
          { required: true, message: '医疗信息不能为空', trigger: 'blur' }
        ],
        childSex: [
          { required: true, message: '孩子怎么会没有性别呢', trigger: 'blur' }
        ],
        childStatus: [
          { required: true, message: '学生状态不能为空', trigger: 'blur' }
        ],
        childTeachingInfo: [
          { required: true, message: '学生教育信息不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 根据计算属性模糊搜索
    list() {
      const searchTableInfo = this.searchTableInfo
      if (searchTableInfo) {
        // filter() 方法创建一个新的数组，新数组中的元素是通过检查指定数组中符合条件的所有元素。
        // 注意： filter() 不会对空数组进行检测。
        // 注意： filter() 不会改变原始数组。
        return this.tableList.filter(data => {
          console.log('success' + data)
          // some() 方法用于检测数组中的元素是否满足指定条件;
          // some() 方法会依次执行数组的每个元素：
          // 如果有一个元素满足条件，则表达式返回true , 剩余的元素不会再执行检测;
          // 如果没有满足条件的元素，则返回false。
          // 注意： some() 不会对空数组进行检测。
          // 注意： some() 不会改变原始数组。
          return Object.keys(data).some(key => {
            // indexOf() 返回某个指定的字符在某个字符串中首次出现的位置，如果没有找到就返回-1；
            // 该方法对大小写敏感！所以之前需要toLowerCase()方法将所有查询到内容变为小写。
            return (
              String(data[key])
                .toLowerCase()
                .indexOf(searchTableInfo) > -1
            )
          })
        })
      }
      return this.tableList
    }
  },
  created() {
    this.fetchData()
    this.getparent()
  },
  methods: {
    // --------------------------------------------动态增加input框---------------------------------------------
    addTrains() {
      this.train.push({
        staffId: store.getters.userId,
        studentId: this.stuId,
        timeStart: '',
        timeEnd: '',
        orgName: '',
        effect: ''
      })
      console.log(this.train)
    },
    deleteItem(item, index) {
      this.train.splice(index, 1)
      // if (this.editType === 2) {
      //   delTrain(item.trainingInstitutionRecordId)
      // }
    },
    // -------------------------------------------------------------------------------------------------------
    formatSex: function(row, column, cellValue) {
      if (cellValue === '1') {
        return '女'
      } else if (cellValue === '0') {
        return '男'
      }
    },

    formatAge: function(row, column, cellValue) {
      if (cellValue === -1) {
        return '未填写'
      } else {
        return cellValue
      }
    },

    handleAvatarSuccess(res, file) {
      this.imageUrl = res.obj.split(';')[0]
      this.student.studentHeadImages = this.imageUrl
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isImage =
        file.type === 'image/png' ||
        file.type === 'image/jpg' ||
        file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传图片只能是 JPG或PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!')
      }
      return isImage && isLt2M
      // return true
    },
    getparent: function() {
      getAllParent(1).then(resp => {
        console.log('爸爸')
        this.father = resp.obj
        console.log(this.father)
      })
      getAllParent(0).then(r => {
        console.log('妈妈')
        this.mother = r.obj
        console.log(this.mother)
      })
    },
    // 每页下拉显示数据
    handleSizeChange: function(size) {
      this.pagesize = size
    },
    // 点击第几页
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage
    },
    handleClick(row) {
      console.log(row)
    },
    fetchData() {
      this.listLoading = true
      getAllMedicalChild(this.BB).then(data => {
        this.tableList = data.obj
        this.listLoading = false
        console.log(data)
      })
      getAllParent(1).then(f => {
        this.father = f.obj
      })
      getAllParent(0).then(m => {
        this.mother = m.obj
      })
    },
    addParent(sex, childId) {
      this.is_add_father = true
    },
    addF(sex, childId) {
      this.is_add_father = true
    },
    handleOpen(title, type, id) {
      this.student = {}
      this.dialogFormVisible = true
      this.title = title
      this.editType = type
      this.stuId = id
      if (type === 2) {
        getChildById(id).then(resp => {
          this.student = resp.obj.student
          console.log(this.student)
          this.train = resp.obj.TrainingInstitutionRecords
          this.student.studentBrothers = String(this.student.studentBrothers)
          this.student.studentSex = String(this.student.studentSex)
          this.imageUrl = this.student.studentHeadImages
          // this.trainList = resp.obj.TrainingInstitutionRecords
          console.log('机构信息？', this.train)
        })
      }
    },
    addM(sex, childId) {
      this.is_add_mother = true
    },
    handleDelete(id, username) {
      this.$confirm('确认删除该学生？姓名为' + username).then(() =>
        deleteChild(id).then(data => {
          this.$notify({
            title: '操作成功',
            type: 'success'
          })
          const totalPage = Math.ceil(
            (this.tableList.length - 1) / this.pagesize
          )
          const page =
            this.currentPage > totalPage ? totalPage : this.currentPage
          this.currentPage = this.currentPage < 1 ? 1 : page
          this.fetchData()
        })
      )
    },
    handleUpdate(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(this.student)
          console.log(this.train)
          newUpdate(this.student, this.train).then((resp) => {
            console.log(resp)
            this.$notify({
              title: '修改成功',
              type: 'success'
            })
            this.fetchData()
          })
          this.student = {}
          this.train = []
          this.dialogFormVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    handleAddUser(formName) {
      var allTrain = this.train_id.toString()
      console.log(allTrain)
      this.student.studentTreatTrainingInstitutionRecords = allTrain.replace(
        /,/g,
        ';'
      )
      this.student.studentBirthtoString = this.student.studentBirth
      this.student.studentJoinCentertoString = this.student.studentJoinCenter
      this.$refs[formName].validate(valid => {
        if (valid) {
          // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa需要得到train_id列表的id（）
          addChild(this.student).then(resp => {
            this.$notify({
              title: '操作成功',
              type: 'success'
            })

            this.fetchData()
            this.train_id = []
            this.form = []
          })
          this.student = []
          this.dialogFormVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    handleAddMother(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          addMother(this.mother).then(resp => {
            this.$notify({
              title: '操作成功',
              type: 'success'
            })
            getAllParent(0)
            this.fetchData()
          })
          this.mother = {}
          this.is_add_mother = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    handleAddFather(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          addFather(this.father).then(resp => {
            this.$notify({
              title: '操作成功',
              type: 'success'
            })

            this.fetchData()
          })
          this.father = {}
          this.is_add_father = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },

    handleClose_f() {
      this.is_add_father = false
      this.father = {}
    },
    handleClose_m() {
      this.is_add_mother = false
      this.mother = {}
    },
    handleClose() {
      this.dialogFormVisible = false
      this.train_id = []
      this.form = []
      this.train = []
      this.student = []
      this.imageUrl = ''
    }
  }
}
</script>

<style scoped>
#main {
  margin-left: 5px;
  margin-right: 5px;
}
#table-area {
  margin-left: 10px;
  margin-right: 10px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 50%;
}
</style>
